package basedao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

/**
 * @Author wuchao66
 * @Date 2023/3/28 13:54
 * @PackageName:com.wuchao.jdbc2.basedao
 * @ClassName: BaseDao
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
public class BaseDao {
    public Connection getConnection1(){
        Connection connection=null;
        Context context=null;
        try {
            context=new InitialContext();
            DataSource lookup =(DataSource) context.lookup("java:comp/env/jdbc163");
            connection=lookup.getConnection();
        } catch (NamingException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    public Connection getConnection(){
        Connection connection=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/t163?useUnicode=true" +
                    "&characterEncoding=utf-8&serverTimeZone=GMT-8","root","root");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public Connection getConnection2(){
        Connection connection=null;
        Context context=null;
        try {
            context=new InitialContext();
         DataSource dataSource=   (DataSource)context.lookup("java:comp/env/jdbc163");
            connection=  dataSource.getConnection();
        } catch (NamingException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public  void closeAll(Connection connection, PreparedStatement preparedStatement,
                          ResultSet resultSet, CallableStatement callableStatement){
        //存储过程 调用的 预处理
        try {
            if(connection!=null&&!connection.isClosed()){
                connection.close();
            }if(preparedStatement!=null&&!preparedStatement.isClosed()){
                preparedStatement.close();
            }if(resultSet!=null&&!resultSet.isClosed()){
                resultSet.close();
            }if(callableStatement!=null&&!callableStatement.isClosed()){
                callableStatement.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
